import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Grid,
  Box,
  Typography,
  CircularProgress,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Tabs,
  Tab,
} from '@mui/material';

// 账单类型定义
const BILL_TYPES = [
  // 收入类型
  { code: 'INCOME', name: '收入', isIncome: true },
  { code: 'SALARY', name: '工资', isIncome: true },
  { code: 'BONUS', name: '奖金', isIncome: true },
  { code: 'INVESTMENT', name: '投资收益', isIncome: true },
  { code: 'REFUND', name: '退款', isIncome: true },
  { code: 'PART_TIME', name: '兼职收入', isIncome: true },
  { code: 'BUSINESS', name: '经营收入', isIncome: true },
  { code: 'RENTAL', name: '租金收入', isIncome: true },
  { code: 'INTEREST', name: '利息收入', isIncome: true },
  { code: 'DIVIDEND', name: '分红收入', isIncome: true },
  { code: 'GIFT', name: '礼金收入', isIncome: true },
  { code: 'OTHER_INCOME', name: '其他收入', isIncome: true },
  
  // 支出类型
  { code: 'EXPENSE', name: '支出', isIncome: false },
  { code: 'FOOD', name: '餐饮', isIncome: false },
  { code: 'TRANSPORT', name: '交通', isIncome: false },
  { code: 'SHOPPING', name: '购物', isIncome: false },
  { code: 'ENTERTAINMENT', name: '娱乐', isIncome: false },
  { code: 'HOUSING', name: '住房', isIncome: false },
  { code: 'UTILITIES', name: '水电费', isIncome: false },
  { code: 'MEDICAL', name: '医疗', isIncome: false },
  { code: 'EDUCATION', name: '教育', isIncome: false },
  { code: 'INSURANCE', name: '保险', isIncome: false },
  { code: 'INVESTMENT_EXPENSE', name: '投资支出', isIncome: false },
  { code: 'OTHER_EXPENSE', name: '其他支出', isIncome: false },
];

const PAYMENT_WAYS = [
  '现金',
  '银行卡',
  '微信支付',
  '支付宝',
  '银行转账',
  '其他'
];

const PAYMENT_PLATFORMS = [
  '工商银行',
  '建设银行',
  '农业银行',
  '中国银行',
  '招商银行',
  '微信',
  '支付宝',
  '其他'
];

const INCOME_SOURCES = [
  '工资收入',
  '奖金收入',
  '投资收益',
  '兼职收入',
  '经营收入',
  '租金收入',
  '利息收入',
  '分红收入',
  '礼金收入',
  '退款收入',
  '其他收入'
];

interface BillFormData {
  amount: string;
  remark: string;
  payUserName: string;
  forUserName: string;
  payWay: string;
  payPlat: string;
  billType: string;
  consumerDate: string;
}

interface BillFormProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: BillFormData) => void;
  title?: string;
  initialData?: Partial<BillFormData>;
  loading?: boolean;
}

export function BillForm({ 
  open, 
  onClose, 
  onSubmit, 
  title = '记录您的每一笔消费',
  initialData = {},
  loading = false 
}: BillFormProps) {
  const [currentTab, setCurrentTab] = useState(0); // 0: 支出, 1: 收入
  const [formData, setFormData] = useState<BillFormData>({
    amount: '',
    remark: '',
    payUserName: '',
    forUserName: '',
    payWay: '',
    payPlat: '',
    billType: 'EXPENSE',
    consumerDate: new Date().toISOString().split('T')[0],
    ...initialData
  });

  const [errors, setErrors] = useState<Partial<BillFormData>>({});

  // 根据当前Tab设置默认的账单类型
  const getDefaultBillType = (tabIndex: number) => {
    if (tabIndex === 0) {
      // 支出Tab
      return 'EXPENSE';
    } else {
      // 收入Tab
      return 'INCOME';
    }
  };

  // 处理Tab切换
  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
    const defaultType = getDefaultBillType(newValue);
    setFormData(prev => ({ ...prev, billType: defaultType }));
    // 清空相关字段
    setFormData(prev => ({ 
      ...prev, 
      payUserName: '', 
      forUserName: '', 
      payWay: '', 
      payPlat: '' 
    }));
  };

  const validateForm = () => {
    const newErrors: Partial<BillFormData> = {};
    
    if (!formData.amount || parseFloat(formData.amount) <= 0) {
      newErrors.amount = '请输入有效的金额';
    }
    
    if (!formData.remark.trim()) {
      newErrors.remark = '请输入备注';
    }
    
    if (!formData.billType) {
      newErrors.billType = '请选择账单类型';
    }
    
    if (!formData.consumerDate) {
      newErrors.consumerDate = '请选择日期';
    }

    // 根据Tab类型验证必填字段
    if (currentTab === 0) {
      // 支出Tab - 需要付款人
      if (!formData.payUserName.trim()) {
        newErrors.payUserName = '请输入付款人';
      }
    } else {
      // 收入Tab - 需要收款人
      if (!formData.forUserName.trim()) {
        newErrors.forUserName = '请输入收款人';
      }
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = () => {
    if (validateForm()) {
      onSubmit(formData);
    }
  };

  const handleInputChange = (field: keyof BillFormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  const selectedBillType = BILL_TYPES.find(type => type.code === formData.billType);
  const isIncome = selectedBillType?.isIncome || false;

  // 根据Tab过滤账单类型
  const getFilteredBillTypes = () => {
    if (currentTab === 0) {
      // 支出Tab - 只显示支出类型
      return BILL_TYPES.filter(type => !type.isIncome);
    } else {
      // 收入Tab - 只显示收入类型
      return BILL_TYPES.filter(type => type.isIncome);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>
        <Box display="flex" alignItems="center" gap={1}>
          <Typography variant="h6">{title}</Typography>
          {selectedBillType && (
            <Typography 
              variant="body2" 
              color={isIncome ? 'success.main' : 'error.main'}
              sx={{ fontWeight: 'bold' }}
            >
              ({selectedBillType.name})
            </Typography>
          )}
        </Box>
      </DialogTitle>
      
      <DialogContent>
        {/* Tab选择器 */}
        <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 2 }}>
          <Tabs value={currentTab} onChange={handleTabChange}>
            <Tab label="支出记录" />
            <Tab label="收入记录" />
          </Tabs>
        </Box>

        <Grid container spacing={2} sx={{ mt: 1 }}>
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="金额"
              type="number"
              value={formData.amount}
              onChange={(e) => handleInputChange('amount', e.target.value)}
              error={!!errors.amount}
              helperText={errors.amount}
              inputProps={{ min: 0, step: 0.01 }}
            />
          </Grid>
          
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="日期"
              type="date"
              value={formData.consumerDate}
              onChange={(e) => handleInputChange('consumerDate', e.target.value)}
              error={!!errors.consumerDate}
              helperText={errors.consumerDate}
              InputLabelProps={{ shrink: true }}
            />
          </Grid>
          
          <Grid item xs={12}>
            <FormControl fullWidth error={!!errors.billType}>
              <InputLabel>账单类型</InputLabel>
              <Select
                value={formData.billType}
                label="账单类型"
                onChange={(e) => handleInputChange('billType', e.target.value)}
              >
                {getFilteredBillTypes().map((type) => (
                  <MenuItem key={type.code} value={type.code}>
                    {type.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          
          {currentTab === 0 && (
            <>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="付款人"
                  value={formData.payUserName}
                  onChange={(e) => handleInputChange('payUserName', e.target.value)}
                  error={!!errors.payUserName}
                  helperText={errors.payUserName}
                />
              </Grid>
              
              <Grid item xs={12} md={6}>
                <FormControl fullWidth error={!!errors.payWay}>
                  <InputLabel>支付方式</InputLabel>
                  <Select
                    value={formData.payWay}
                    label="支付方式"
                    onChange={(e) => handleInputChange('payWay', e.target.value)}
                  >
                    {PAYMENT_WAYS.map((way) => (
                      <MenuItem key={way} value={way}>{way}</MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
            </>
          )}
          
          {currentTab === 1 && (
            <>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="收款人"
                  value={formData.forUserName}
                  onChange={(e) => handleInputChange('forUserName', e.target.value)}
                  error={!!errors.forUserName}
                  helperText={errors.forUserName}
                />
              </Grid>
              
              <Grid item xs={12} md={6}>
                <FormControl fullWidth error={!!errors.payPlat}>
                  <InputLabel>收入来源</InputLabel>
                  <Select
                    value={formData.payPlat}
                    label="收入来源"
                    onChange={(e) => handleInputChange('payPlat', e.target.value)}
                  >
                    {INCOME_SOURCES.map((source) => (
                      <MenuItem key={source} value={source}>{source}</MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
            </>
          )}
          
          <Grid item xs={12}>
            <TextField
              fullWidth
              label="备注"
              multiline
              rows={3}
              value={formData.remark}
              onChange={(e) => handleInputChange('remark', e.target.value)}
              error={!!errors.remark}
              helperText={errors.remark}
            />
          </Grid>
        </Grid>
      </DialogContent>
      
      <DialogActions>
        <Button onClick={onClose} disabled={loading}>
          取消
        </Button>
        <Button 
          onClick={handleSubmit} 
          variant="contained" 
          disabled={loading}
          startIcon={loading ? <CircularProgress size={16} /> : undefined}
        >
          {loading ? '保存中...' : '保存'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
